/*
 * @Descripttion:
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2022-11-28 17:44:53
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2022-11-29 17:23:46
 */
package id

import (
	"gitee.com/g_boot/gfextend/types"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
)

var (
	idGenList map[string]IdGenerator
)

func init() {
	idGenList = make(map[string]IdGenerator)
}

// ID生成器
type IdGenerator interface {
	// 生成器名称
	GetName() string

	// 生成id
	GenId(pairs ...types.Pair) string
}

func Instance(name string) IdGenerator {
	obj, _ := Get(name)
	return obj
}

// 注册
func Regist(name string, IdGen IdGenerator) error {

	_, ok := Get(name)
	if ok {
		err := gerror.NewCode(gcode.CodeOperationFailed, "ID生成器已存在")

		return err
	}

	idGenList[name] = IdGen

	return nil

}

// 获取
func Get(name string) (IdGenerator, bool) {

	val, ok := idGenList[name]

	return val, ok

}

// 注销
func UnRegist(name string) error {
	delete(idGenList, name)

	return nil
}


// 替换
func Replace(name string, IdGen IdGenerator) error {
	idGenList[name] = IdGen

	return nil
}
